--[[
    @api: /device/device_upload
]]
local args = ngx.req.get_uri_args()

local register_gateway_info = function()
    local gateway_id = args.gateway_id
    if not common_util.check_args(1, gateway_id) then
        common_util.exit(200, 0, nil, "101", "gateway_id is missing")
    end
    local signature = "123456abc" --网关默认初始化签名
    if args.new_signature then
        --如果需要系统生成签名
        signature = common_util.luuid()
    end
    mqtt_util.add_emq_user(gateway_id, signature)
    mqtt_util.add_user_acl(gateway_id, gateway_id .. "/" .. common_config.mqtt_config.change_topic, "sub") --给网关添加订阅控制主题消息的权限
    mqtt_util.add_user_acl(gateway_id, gateway_id .. "/" .. common_config.mqtt_config.view_topic, "pub") --给网关添加发布通知主题消息的权限
    common_util.exit(200, 1, {["signature"] = signature}, "", "success")
end

local history_data_upload = function()
    ngx.req.read_body()
    local gateway_id = args.gateway_id
    local device_id = args.device_id
    local signature = args.signature
    if not common_util.check_args(3, gateway_id, device_id, signature) then
        common_util.exit(200, 0, nil, "101", "param is missing")
    end 

    if true ~= mqtt_util.verify_device(gateway_id, signature) then
        common_util.exit(200, 0, nil, "106", "signature is error")
    end

    local data,is_ok = common_util.get_data()
    local history_data = cjson_safe.decode(data) or {}
    if not next(history_data) then
        common_util.exit(200, 0, nil, "101", "body is missing")
    end
    
    --[[
        @history_data:
        {
            "time":12334344, #设备上传时间戳 单位S
            "device_id": "xxxxxx"
            .....
        }
    ]]
    history_data["time"] = ngx.time()
    history_data["device_id"] = device_id
    local result,boo=redis_util.redis_cmd('async',"lpush",'history_list_0', cjson_safe.encode(history_data)) --写入redis队列
    if true ~= bool then    
        common_util.exit(200, 0, nil, "500", "redis is error")
    end
    common_util.exit(200, 1, nil, "", "upload is success")
end

--验证设备请求参数和身份验证
local verify_device_request = function()
    local gateway_id = args.gateway_id
    local signature = args.signature
    if not common_util.check_args(2, gateway_id, signature) then
        common_util.exit(200, 0, nil, "101", "param is missing")
    end 

    if true ~= mqtt_util.verify_device(gateway_id, signature) then
        common_util.exit(200, 0, nil, "106", "signature is error")
    end

    return gateway_id, signature
end

local update_device_data = function()
    local gateway_id, signature = verify_device_request()
    local device_id = args.device_id
    if not common_util.check_args(1, device_id) then
        common_util.exit(200, 0, nil, "101", "device_id is missing")
    end

    local sql = "select * from tb_device_common_info where gateway_id="..ngx.quote_sql_str(gateway_id).." and device_id="..ngx.quote_sql_str(device_id)
    local data,bool = common_util.db_query_common(sql,common_config.db_user_info_addr)
    if false == bool  then
        --connection:over()
        common_util.exit(200, 0, nil, "500", "mysql is error")
    end
    if next(data) then
        if 0 == #data then
            --如果设备都被删除了
            local sql = "insert into tb_device_common_info set gateway_id="..ngx.quote_sql_str(gateway_id)..",device_id="..ngx.quote_sql_str(device_id)..",device_name="..ngx.quote_sql_str("设备"..string.sub(device_id, -4, -1))
            if tonumber(args.device_type) then
                sql = sql ..",device_type="..tonumber(args.device_type)
            end
            local data,bool = common_util.db_query_common(sql,common_config.db_user_info_addr)
            if false == bool  then
                --connection:over()
                common_util.exit(200, 0, nil, "500", "mysql is error")
            end
            --查看拥有此网关的用户
            local sql = "select user_id from tb_gateway_info where status=1 and gateway_id="..ngx.quote_sql_str(gateway_id)
            local data,bool = common_util.db_query_common(sql,common_config.db_user_info_addr)
            if false == bool  then
                --connection:over()
                common_util.exit(200, 0, nil, "500", "mysql is error")
            end
            if next(data) then
                --将设备添加到网关的管理员用户
                for _, tem_data in pairs(data) do
                    local sql = "inser into tb_user_device_info set gateway_id="..ngx.quote_sql_str(gateway_id)..",device_id="..ngx.quote_sql_str(device_id)
                        ..",status=1"..",user_id="..tem_data.user_id..",authority=7"
                    common_util.db_query_common(sql,common_config.db_user_info_addr)
                end
            end
        else
            --更新设备信息
            if tonumber(args.device_type) then
                local sql = "update tb_device_common_info set device_type="..args.device_type.." where  gateway_id="..ngx.quote_sql_str(gateway_id)..",device_id="..ngx.quote_sql_str(device_id)
                local data,bool = common_util.db_query_common(sql,common_config.db_user_info_addr)
                if false == bool  then
                    --connection:over()
                    common_util.exit(200, 0, nil, "500", "mysql is error")
                end
            end
        end
    end
    common_util.exit(200, 1, nil, "", "success")
end

local handle_alarm_requst = function()
    ngx.req.read_body()
    local gateway_id, signature = verify_device_request()
    local device_id = args.device_id
    if not common_util.check_args(1, device_id) then
        common_util.exit(200, 0, nil, "101", "device_id is missing")
    end

    local data,is_ok = common_util.get_data()
    local alarm_data = cjson_safe.decode(data) or {}
    if not next(alarm_data) then
        common_util.exit(200, 0, nil, "101", "body is missing")
    end
    
    local content = alarm_data.content
    if not content then
        common_util.exit(200, 0, nil, "101", "content is missing")
    end

    local sql = "select * from tb_device_common_info where gateway_id="..ngx.quote_sql_str(gateway_id)..",device_id="..ngx.quote_sql_str(device_id).." limit 1"
    local _data,bool = common_util.db_query_common(sql,common_config.db_user_info_addr)
    if false == bool  then
        --connection:over()
        common_util.exit(200, 0, nil, "500", "mysql is error")
    end
    if not next(_data) then
        common_util.exit(200, 0, nil, "101", "cannot find device")
    end
    local device_info = _data[1] --设备详细信息

    local sql = "select user_id from tb_user_device_info where gateway_id="..ngx.quote_sql_str(gateway_id)..",device_id="..ngx.quote_sql_str(device_id)
    local res_device_data,bool = common_util.db_query_common(sql,common_config.db_user_info_addr)
    if false == bool  then
        --connection:over()
        common_util.exit(200, 0, nil, "500", "mysql is error")
    end

    if next(res_device_data) then
        for _, user_id in pairs(data) do
            --获取用户微信openid
            local sql = "select account from tb_user_info where user_id="..user_id.." and type=0 and status=1 limit 1"
            local res_data,bool = common_util.db_query_common(sql,common_config.db_user_info_addr)
            if false == bool  then
                --connection:over()
                common_util.exit(200, 0, nil, "500", "mysql is error")
            end
            if next(res_data) then
                --向用户推送模板消息
                wechat_util.template_message(res_data[1].account, device_info.device_id, device_info.device_name, content)
            end
        end
    end
end

local handle_band_success_quest = function()
    --local gateway_id, signature = verify_device_request()
    local gateway_id = args.gateway_id
    local signature = args.signature

    if not common_util.check_args(2, gateway_id, signature) then
        common_util.exit(200, 0, nil, "101", "param is missing")
    end

    local sql = "select status from tb_gateway_info where gateway_id="..ngx.quote_sql_str(gateway_id) .. " and signature=" .. ngx.quote_sql_str(signature)
    local data,bool = common_util.db_query_common(sql,common_config.db_user_info_addr)
    if false == bool  then
        --connection:over()
        common_util.exit(200, 0, nil, "500", "mysql is error")
    end

    if 0 < #data then
        if 1 == tonumber(data[1].status) then
            common_util.exit(200, 0, nil, "101", "the gateway is not your...")
        end
    else
        common_util.exit(200, 0, nil, "101", "the gateway is not exits")
    end
    
    --检查该网关是否在绑定中
    local sql = "update tb_gateway_info set status=1 where gateway_id="..ngx.quote_sql_str(gateway_id) .. " and signature=" .. ngx.quote_sql_str(signature)
    local data,bool = common_util.db_query_common(sql,common_config.db_user_info_addr)
    if false == bool  then
        --connection:over()
        common_util.exit(200, 0, nil, "500", "mysql is error")
    end
    mqtt_util.add_emq_user(gateway_id, signature)
    mqtt_util.add_user_acl(gateway_id, gateway_id .. "/" .. common_config.mqtt_config.change_topic, "sub") --给网关添加订阅控制主题消息的权限
    mqtt_util.add_user_acl(gateway_id, gateway_id .. "/" .. common_config.mqtt_config.view_topic, "pub") --给网关添加发布通知主题消息的权限
    common_util.exit(200, 1, nil, "", "success")
end

local method = {
    ["band_success_quest"] = handle_band_success_quest, --处理绑定网关成功请求,网关接受绑定请求后,更新信息
    ["register_gateway_info"] = register_gateway_info, --用于手动注册网关
    ["history_data_upload"] = history_data_upload, --设备上传历史数据
    ["update_decice_data"] = update_device_data, --网关更新连接设备信息
    ["handle_alarm_requst"] = handle_alarm_requst, --处理报警请求
}

if not method[args.type] then
    common_util.exit(200, 0, nil, "101", "type is missing")
end

method[args.type]() 
common_util.exit(200, 0, nil, "101", "param is error")